<template>
	<view class="im-body">
		<view class="content1" @touchstart="hideDrawer" @touchmove.stop.prevent>
			<scroll-view :style="{height:height+'px'}" class="msg-list" scroll-y="true"
				:scroll-with-animation="scrollAnimation" :scroll-top="scrollTop" :scroll-into-view="scrollToView"
				:refresher-enabled="refresher" :refresher-triggered="triggered" refresher-background="#EDEDED"
				@refresherpulling="onPulling" @refresherrefresh="onRefresh" @refresherrestore="onRestore"
				@refresherabort="onAbort">
				<!-- 加载历史数据waitingUI -->
				<view class="loading" v-if="loading">
					<view class="spinner">
						<view class="rect1"></view>
						<view class="rect2"></view>
						<view class="rect3"></view>
						<view class="rect4"></view>
						<view class="rect5"></view>
					</view>
				</view>
				<div id="messageList">
					<view v-for="(item,index) in msgList" :key="index" :id="'id_'+item.msgID">
						<!-- 用户消息 -->
						<div class="row"
							v-if="item.status !=7 && item.status !=3 && item.status!=4 && item.elemType!=2">
							<view class="time" v-if="timeFliter(item.timestamp,index)!=''">
								{{timeFliter(item.timestamp,index)}}
							</view>
							<view class="ch" v-if='item.status == 6'>
								{{item.sender ==user.userId?'您':'对方'}}撤回了一条消息
							</view>
							<view class="time" v-if="item.elemType==100 || item.elemType==101">
								{{item.Text}}
							</view>
							<view class="time" v-if="item.elemType==10">
								{{item.actionText}}
							</view>
							<view class="time" v-if="item.elemType==104">
								<view class="yetOrder">
									<view class="yetOrderText">{{item.Text}}</view>
									<view class="yetOrderAction" @click="customMsgClick(item)">,去下单</view>
								</view>
							</view>
							<!-- 自己发出的消息 -->
							<view class="my"
								v-if="item.sender==user.userId && item.status!=6 && item.elemType!=10 && item.elemType!=100&& item.elemType!=104">
								<!-- 左-消息 -->
								<view class="left">
									<image v-if="item.status==10" src='../../static/im/tip.png' class="sendtip"
										@click="sendAgain(item)"></image>
									<image v-if="item.sending==true &&( item.elemType==1 || item.elemType ==4)"
										src="../../static/im/loading.gif" style="height: 50rpx; width: 50rpx;"></image>
									<!-- 文字消息 -->
									<view v-if="item.elemType==1" class="bubble" @tap="fndbClick(item)"
										@longpress="onLongPress" :data-item='item' :data-index="index"
										:data-sender="item.sender" :data-timestamp='item.timestamp'>
										<!-- style="user-select:all" -->
										<rich-text :nodes="nodesFliter(item.textElem.text)"></rich-text>
									</view>
									<view v-if="item.elemType==3" style="padding:0rpx; " class="playview"
										:style="{height:item.height +'rpx',width:item.width +'rpx'}"
										:data-url='item.imageElem.imageList[0].url' @click="previewImage($event)">
										<image lazy-load :class="item.loaded || 'loading'" @load="onImageLoad(index)"
											@error="onImageError( index)" style="border-radius: 10rpx;"
											:src="item.imageElem.imageList[0].url" class="img"
											:style="{height:item.height +'rpx',width:item.width +'rpx'}"
											@longpress="onLongPress" :data-item='item' :data-index="index"
											:data-sender="item.sender" :data-timestamp='item.timestamp'>
										</image>
										<image v-if="item.sending" class="playIcon" src="../../static/im/loading.gif"></image>
									</view>
									<view v-if="item.elemType==4" class="bubble soundbox" @longpress="onLongPress"
										:data-item='item' :data-index="index" :data-timestamp='item.timestamp'
										:data-sender="item.sender" :style="{width: item.width +'rpx'}"
										@click="playVoiceUrl(item)">
										<view>
											{{item.soundElem.duration}}''
										</view>
										<image v-if="item.msgID!=playSoundMsgId" src="../../static/im/audio-play.png"
											class="radio-left">
										</image>
										<image v-if="item.msgID==playSoundMsgId" src="../../static/im/audio-play.gif"
											class="radio-left">
										</image>
									</view>
									<view v-if="item.elemType==5" class="bubble" @longpress="onLongPress"
										:data-item='item' :data-index="index" :data-timestamp='item.timestamp'
										:data-sender="item.sender"
										:style="{width: item.width +  'rpx', height: item.height + 'rpx'}"
										style=" position: relative;padding:0rpx;" :url="item.videoElem.videoPath">
										<image v-if="item.videoElem.videoPath ==''" src="../../static/im/loading.gif"
											style="position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);width:80rpx;height: 80rpx;">
										</image>
										<!-- <j-video v-if="item.videoElem.videoPath !=''" :url="item.videoElem.videoPath"
										:poster="item.videoElem.snapshotPath" :height="item.height" :width="item.width"
										:videoduration="item.videoElem.duration" :sending="item.sending">
									</j-video> -->
										<view class="playview" @click="playVideo(item)">
											<image v-if="!item.sending" style="z-index: 5;" class="playIcon"
												src="../../static/im/play.png"></image>
											<image style="border-radius: 10rpx;" v-if="item.videoElem.videoPath !=''"
												:src="item.videoElem.snapshotPath"
												:style="{height:item.height +'rpx',width:item.width +'rpx'}"></image>
											<view class="videotime">
												{{timeConverter(item.videoElem.duration)}}
											</view>
											<image v-if="item.sending" class="playIcon" src="../../static/im/loading.gif">
											</image>
										</view>

									</view>

									<view v-if="item.elemType==11" class="bubble"
										:style="{width: item.width +  'rpx', height: item.height + 'rpx'}"
										style=" position: relative;padding:0rpx;">
										<view class="playview" @click="playVideo(item)">
											<image style="z-index: 5;" class="playIcon" src="../../static/im/play.png"></image>
											<image style="border-radius: 10rpx;" v-if="item.snapshotPath !=''"
												:src="item.snapshotPath"
												:style="{height:item.height +'rpx',width:item.width +'rpx'}"></image>
											<view class="videotime">
												{{timeConverter(item.Second)}}
											</view>
										</view>
									</view>
								</view>
								<!-- 右-头像 -->
								<view class="right" @click="persondetail(user.userUrl)">
									<image :src="item.faceUrl || '../../static/im/me_chat.png'" class="personImg"></image>
								 
								</view>
							</view>
							<!-- 别人发出的消息 -->
							<view class="other"
								v-if="item.sender!=user.userId && item.status!=6 && item.elemType!=10 && item.elemType!=100 && item.elemType!=104">
								<!-- 左-头像 -->
								<view class="left" @click="persondetail(user.otherUrl)">
									<image :src="item.faceUrl || '../../static/im/doc_chat.png'" class="personImg"></image>
									 
								</view>
								<!-- 右-用户名称-时间-消息 -->
								<view class="right">
									<!-- 文字消息 -->
									<view v-if="item.elemType==1" class="bubble" @tap="fndbClick(item)"
										@longpress="onLongPress" :data-item='item' :data-index="index"
										:data-timestamp='item.timestamp' :data-sender="item.sender">
										<rich-text :nodes="nodesFliter(item.textElem.text)">
										</rich-text>
									</view>
									<view v-if="item.elemType==3" style="padding:0rpx; margin: 0rpx !important; "
										@longpress="onLongPress" :data-item='item'
										:style="{height:item.height +'rpx',width:item.width +'rpx'}"
										:data-sender="item.sender" :data-index="index" :data-timestamp='item.timestamp'
										:data-url='item.imageElem.imageList[0].url' @click="previewImage($event)">

										<image lazy-load :class="item.loaded || 'loading'" @load="onImageLoad(index)"
											@error="onImageError( index)" style="border-radius: 10rpx;"
											:src="item.imageElem.imageList[0].url" class="img"
											:style="{height:item.height +'rpx',width:item.width +'rpx'}">
										</image>
									</view>
									<view v-if="item.elemType==4" class="bubble soundbox" @longpress="onLongPress"
										:data-item='item' :data-index="index" :data-timestamp='item.timestamp'
										:data-sender="item.sender" :style="{width: item.width +'rpx'}"
										@click="playVoiceUrl(item)" :url="item.soundElem.path">

										<image v-if="item.msgID!=playSoundMsgId" src="../../static/im/audio-play.png"
											class="radio-right">
										</image>
										<image v-if="item.msgID==playSoundMsgId" src="../../static/im/audio-play.gif"
											class="radio-right">
										</image>
										<view>
											{{item.soundElem.duration}}''
										</view>
									</view>
									<!--  -->
									<view v-if="item.elemType==5" class="bubble" @longpress="onLongPress"
										:data-item='item' :data-index="index" :data-timestamp='item.timestamp'
										:data-sender="item.sender"
										:style="{width: item.width +  'rpx', height: item.height + 'rpx'}"
										style="position: relative;padding:0rpx;" :url="item.videoElem.videoPath">
										<image v-if="item.videoElem.videoPath ==''" src="../../static/im/loading.gif"
											style="position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);width:80rpx;height: 80rpx;">
										</image>
										<!-- <j-video v-if="item.videoElem.videoPath !=''" :url="item.videoElem.videoPath"
										:poster="item.videoElem.snapshotPath" :height="item.height" :width="item.width"
										:videoduration="item.videoElem.duration">
									</j-video> -->
										<view class="playview" @click="playVideo(item)">
											<image v-if="!item.sending" style="z-index: 5;" class="playIcon"
												src="../../static/im/play.png"></image>
											<image style="border-radius: 10rpx;" v-if="item.videoElem.videoPath !=''"
												:src="item.videoElem.snapshotPath"
												:style="{height:item.height +'rpx',width:item.width +'rpx'}"></image>
											<view class="videotime">
												{{timeConverter(item.videoElem.duration)}}
											</view>
										</view>
									</view>
									<view v-if="item.elemType==11" class="bubble"
										:style="{width: item.width +  'rpx', height: item.height + 'rpx'}"
										style=" position: relative;padding:0rpx;">
										<view class="playview" @click="playVideo(item)">
											<image style="z-index: 5;" class="playIcon" src="../../static/im/play.png"></image>
											<image style="border-radius: 10rpx;" v-if="item.snapshotPath !=''"
												:src="item.snapshotPath"
												:style="{height:item.height +'rpx',width:item.width +'rpx'}"></image>
											<view class="videotime">
												{{timeConverter(item.Second)}}
											</view>
										</view>
									</view>

									<view v-if="item.elemType==12" @click="customMsgClick(item)">
										<view class="question">
											<view class="questionTitle qstTitle">
												<view class="img">
													<image src="../../static/im/question.png"></image>
												</view>
												<view class="title">{{item.Title}}</view>
											</view>
											<view class="questionContent">
												{{item.Describe}}
											</view>
											<view class="action actionBlue">
												查看详情
											</view>
										</view>
									</view>
									<view v-if="item.elemType==102" @click="customMsgClick(item)">
										<view class="question">
											<view class="questionTitle medicneTitle">
												<view class="img">
													<image src="../../static/im/medicine.png"></image>
												</view>
												<view class="title">{{item.Title}}</view>
											</view>
											<view class="questionContent">
												{{item.Describe}}
											</view>
											<view class="action actionPerplue">
												查看详情
											</view>
										</view>
									</view>
								</view>
							</view>
						</div>
					</view>
				</div>
			</scroll-view>
		</view>
		<!-- 底部输入栏 -->
		<view v-if="user.iscan==0" class="input-box" :class="popupLayerClass" @touchmove.stop.prevent="discard">
			<view class="voice">
				<image @tap="switchVoice" src="../../static/im/jp.png" v-if="isVoice" class="iconImg changeState"></image>
				<image @tap="switchVoice" src="../../static/im/voice.png" v-if="!isVoice" class="iconImg changeState"></image>
			</view>
			<view class="textbox">
				<view class="voice-mode" :class="[isVoice?'':'hidden',recording?'recording':'']"
					@touchstart="voiceBegin" @touchmove.stop.prevent="voiceIng" @touchend="voiceEnd"
					@touchcancel="voiceCancel">{{voiceTis}}</view>
				<view class="text-mode" :class="isVoice?'hidden':''">
					<view class="box">
						<scroll-view scroll-y="true" :style="{height:38*setHeight.line+'rpx'}">
							<textarea fixed="true" @linechange="lineChange" :adjust-position="false"
								@keyboardheightchange="keyboardheightchange" maxlength="1000" cursor-spacing="12"
								:focus="textFoucs" @focus="textareaFocus" placeholder-class="placeholder"
								placeholder="输入文字" auto-height="true" v-model="textMsg" />
							</textarea>
						</scroll-view>
					</view>

				</view>
			</view>
			<view class="viewVideo" v-if="textMsg.length==0 || isVoice" @tap="recordVideo">
				<!-- <view class="icon "> -->
				<image src="../../static/im/video.png" class="iconImg"></image>
				<!-- </view> -->
			</view>
			<view class="send" :class="isVoice || textMsg.length==0 ?'hidden':''" @touchend.prevent="sendText">
				<!-- @tap="sendText" -->
				<view class="btn">发送</view>
			</view>
			<view class="more" v-if="textMsg.length==0 || isVoice" @tap="showMore">
				<image src="../../static/im/more.png" class="iconImg"></image>
			</view>
		</view>
		<view v-if="user.iscan==1" style="padding:0 !important" class="input-box" :class="popupLayerClass"
			@touchmove.stop.prevent="discard">
			<view  style="width:750rpx; text-align: center; height: 115rpx;line-height: 110rpx;background-color: #D5D5D5;color: #999;">
				 医生接诊中才可以发消息
			</view>
		</view>
		<!-- 抽屉栏 -->
		<view class="popup-layer" :class="popupLayerClass" @touchmove.stop.prevent="discard">
			<!-- 表情 -->
			<swiper class="emoji-swiper" :class="{hidden:hideEmoji}" indicator-dots="true" duration="150">
				<swiper-item v-for="(page,pid) in emojiList" :key="pid">
					<view v-for="(em,eid) in page" :key="eid" @tap="addEmoji(em)">
						<image mode="widthFix" :src="'../../static/im/emoji/'+em.url"></image>
					</view>
				</swiper-item>
			</swiper>
			<!-- 更多功能 相册-拍照 -->
			<view class="more-layer" :class="{hidden:hideMore}">
				<view class="list">
					<view class="listitem">
						<view class="box" @tap="chooseImage">
							<image src="../../static/im/iconPic.png"></image>
						</view>
						<view class="tip">
							相册
						</view>
					</view>
					<view class="listitem">
						<view class="box" @tap="sendVideoMessage">
							<image src="../../static/im/iconVideo.png"></image>
						</view>
						<view class="tip">
							短视频
						</view>
					</view>
					<view class="listitem" v-if="clienttype ==0">
						<view class="box" @tap="videoChat">
							<image src="../../static/im/iconCon.png"></image>
						</view>
						<view class="tip">
							视频通话
						</view>
					</view>
					<!-- <view class="listitem" v-if="clienttype ==0">
						<view class="box" @tap="fastreply">
							<image src="../../static/im/kjhf.png"></image>
						</view>
						<view class="tip">
							快捷回复
						</view>
					</view>
					<view class="listitem" v-if="clienttype ==0">
						<view class="box" @tap="medPres">
							<image src="../../static/im/blcf.png"></image>
						</view>
						<view class="tip">
							病历处方
						</view>
					</view> -->
					<view class="listitem" v-for="(item,index) in gjx">
						<view class="box" @tap="itemClick(item)">
							<image :src="item.Img"></image>
						</view>
						<view class="tip">
							{{item.Text}}
						</view>
					</view>
				</view>
			</view>
		</view>
		<view :style="{height:0+'px'}"></view>
		<!-- 录音UI效果 -->
		<view class="record" :class="recording?'':'hidden'">
			<view class="ing" :class="willStop?'hidden':''">
				<!-- <view class="icon luyin2"></view> -->
				<image src="../../static/im/recording.gif" style="height: 80%;width: 60%;"></image>
			</view>
			<view class="cancel" :class="willStop?'':'hidden'">
				<view class="icon chehui"></view>
			</view>
			<view class="tis" :class="willStop?'change':''">{{recordTis}}</view>
		</view>

		<!-- 长按效果-->
		<view class="shade" v-show="showShade" @tap="hidePop">
			<view class="pop" :style="popStyle" :class="{'show':showPop}">
				<view v-for="(item,index) in popButton.filter(p=>p.show==true)" :key="index" @tap="pickerMenu"
					:data-code="item.code" :data-index="index">{{item.text}}
				</view>
			</view>
		</view>
		<!-- 文字双击效果-->
		<view class="textSceen" v-show="showSceen" @tap="hideSceen">
			<scroll-view scroll-y="true" class="sceenContent">
				<!-- <view>{{doubleText}}</view> -->
				<!-- -->
				<rich-text :nodes="nodesFliter(doubleText)" style="padding:50rpx"></rich-text>
			</scroll-view>
			<view class="sceenTool" @tap="hideSceen">
				关闭
			</view>
		</view>
		<view class="videoSceen" v-if="showVideo">
			<!-- @timeupdate="timeupdate" @fullscreenchange="fullscreenchange"  @error="videoErrorCallback"  -->
			<view class="sceenContent">
				<video id="myVideo" direction="0" class="video" :src="videoUrl" autoplay="true">
				</video>
			</view>
			<view class="sceenTool" @tap="hidePayer">
				关闭
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	import {
		throttle
	} from '../../lobster-sdk/js/throttle.js' 
	
	export default {
		name: "trtc-room",
		data() {
			return {
				isInit: false, //初始化
				height: 800,
				setHeight: {
					keyHeight: 0, //键盘高度
					inputHeight: 0, //输入框高度
					line: 1,
				},
				loading: 'true', //加载中效果
				//user: {},
				//文字消息
				textMsg: '',
				//消息列表
				isHistoryLoading: false,
				scrollAnimation: false,
				scrollTop: 0,
				scrollToView: '',
				msgList: [],
				imglist: [],
				lastMessageID: '', //最后一条消息id
				// 抽屉参数
				popupLayerClass: '',
				// more参数
				hideMore: true,
				count: 60,
				isVoice: false,
				voiceTis: '按住 说话',
				recordTis: "手指上滑 取消发送",
				recording: false,
				willStop: false,
				initPoint: {
					identifier: 0,
					Y: 0
				},
				recordTimer: null,
				clickIng: false,
				recordLength: 0,
				RECORDER: uni.getRecorderManager(),
				//播放语音相关参数
				AUDIO: uni.createInnerAudioContext(),
				playMsgid: null,
				VoiceTimer: null,
				soundMax: 60, //语音最长消息秒数
				soundcountdown: 10, //最后多少秒开始倒计时
				pageCount: 15, //每次获取腾讯云数量
				mysavedFilePath: '',
				platform: 'android',
				playSoundMsgId: '', //当前播放的语音信息的msgId
				baseP: 300, //基本比例
				hideEmoji: true,
				emojiList: this.$lobster.im.emojiList,
				//表情图片图床名称 ，由于我上传的第三方图床名称会有改变，所以有此数据来做对应，您实际应用中应该不需要
				onlineEmoji: this.$lobster.im.onlineEmoji,

				// ---   长按
				/* 窗口尺寸 */
				winSize: {},
				/* 显示遮罩 */
				showShade: false,
				/* 显示操作弹窗 */
				showPop: false,
				/* 弹窗按钮列表 */
				popButton: [{
					code: 'ch',
					text: "撤回",
					show: false,
				}, {
					code: 'fz',
					text: '复制',
					show: true
				}, ],
				/* 弹窗定位样式 */
				popStyle: "",

				/* 选择的用户下标 */
				pickerMsgIndex: -1,
				// --  长按结束
				showSceen: false, //大屏显示内容
				//双击
				index: 0,
				start_time: 0,
				end_time: 0,
				doubleText: '', //双击内容文本


				triggered: false,
				_freshing: false,
				refresher: true, //下拉事件是否开启

				textFoucs: false,
				showVideo: false,
				videoUrl: '',
				VideoContext: {},
				keyHeight: 0
			}
		},
		props: {
			user: {
				type: Object,
				value: {}
			},
			//是否有订单
			haveOrder: {
				type: String,
				value: '0'
			},
			//是否自定义标题
			isCustomTitile: {
				type: Boolean,
				value: false
			},
			//用户端类型  0 医生  1 患者
			clienttype: {
				type: String,
				value: 0
			},
			gjx: {
				type: Array,
				value: [],
			}
		},
		computed: {
			...mapState({
				currNewMessageList: state => state.im.currNewMessageList,
				imUpdateIndex: state => state.im.imUpdateIndex,
			})
		},
		watch: {
			user(newval, oldval) {
				console.log(newval);
				this.platform = uni.getSystemInfoSync().platform;
				this.setScallHeight();
				this.initBaseData();
			},
			haveOrder(newval, oldval) {
				console.log(newval + '_' + oldval);
			},
			//同步当前会话数据
			currNewMessageList(newVal, oldVal) {
				console.log("33333333333333");
				//console.log(newVal)
				if (newVal.length) {
					if (newVal.length == oldVal.length && newVal[0].msgID == oldVal[0].msgID) {
						return;
					}
					this.messageConverter(newVal);
					this.msgList.push(...newVal);
					this.$nextTick(() => {
						this.scrollTop = 5000 + Math.random()
					})
				}
			},
			//更新标志
			imUpdateIndex(newVal, oldVal) {
				//console.log(newVal)
				this.$store.commit('toggleCurrentActive', this.user.touser);
			}
		},
		onResize() {
			this.setScallHeight();
		},
		methods: {
			setScallHeight: function() {
				console.log(this.user);
				console.log(this.setHeight.inputHeight);
				if (!this.setHeight.inputHeight) {
					let actionHeight = this.winSize.width * 115 / 750;
					// if (this.user.iscan == 1) {
					// 	actionHeight = 0;
					// }
					this.setHeight.inputHeight = actionHeight;
				}
				// if (this.user.iscan == 1) {
				// 	this.setHeight.inputHeight = 0;
				// }
				
				var allHieight = this.winSize.height - this.setHeight.inputHeight;
				if (!this.hideMore) {
					allHieight -= this.winSize.width * 0.42;
				}
				if (this.setHeight.keyHeight) {
					allHieight -= this.setHeight.keyHeight;
					allHieight -= this.winSize.statusBarHeight;
					allHieight -= 44;
					allHieight += (this.winSize.screenHeight - this.winSize.height);
				} else {
					if (this.isCustomTitile) {
						allHieight -= this.winSize.statusBarHeight;
						allHieight -= 44;
					}
				}
				//console.log(this.setHeight)
				this.height = allHieight;
				setTimeout(() => {
					this.scrollTop = 9999 + Math.random() * 100;
				}, 300)
				return;
			},
			//转换路径
			messageConverter(list) {
				var self = this;
				list.forEach(function(item, index) {
					if (item.elemType == 2) { //自定义消息
						self.$lobster.im.getSignalingInfo(item.msgID, res => {
							if (res && res.info) {
								item.elemType = 10; //信令  自定义类型
								item.actionType = res.info.actionType;
								item.actionText = self.$lobster.im.actionConverter(item.actionType, res.info.data);
							} else {
								self.$lobster.im.getCustomMessageData2String(item.msgID, res => {
									//console.log(res);
									self.customMsgConverter(item, res);
								})
							}
						});
					}
					if (item.elemType == 3) { //图片
						self.imglist.push(item.imageElem.imageList[0].url);
						var width = item.imageElem.imageList[0].width;
						var height = item.imageElem.imageList[0].height;
						var custom = {};
						try {
							custom = JSON.parse(item.cloudCustomData);
						} catch (res) {

						}
						// if(custom && custom.bq)
						// {}
						if (!custom.bq) {
							var p = width / height;
							if (p >= 1) {
								width = self.baseP;
								height = width / p;
							} else {
								height = self.baseP;
								width = height * p
							}
						}
						item.height = height;
						item.width = width;
					}
					if (item.elemType == 4) { //语音
						//var w = parseInt(item.soundElem.duration) * 40;
						item.width = self.$lobster.im.soundLength(item.soundElem.duration, self.winSize
							.screenWidth);
						if (item.status != 2) return;
						self.$lobster.im.downloadSound(item.msgID, down => {
							self.$set(item.soundElem, "path", down.url);
						}, result => {})
					} else if (item.elemType == 5) { //短视频
						console.log(item);
						var width = parseFloat(item.videoElem.snapshotWidth);
						var height = parseFloat(item.videoElem.snapshotHeight);
						var p = width / height;
						if (p >= 1) {
							width = self.baseP;
							height = width / p;
						} else {
							height = self.baseP;
							width = height * p
						}
						item.height = height;
						item.width = width;
						//return;
						if (item.status != 2) return;
						self.$lobster.im.downloadVideoImg(item.msgID, down => {
							setTimeout(function() {
								if (down.url) {
									var pro = self.$lobster.im.saveFile(down.url);
									pro.then(re => {
										self.$set(item.videoElem, "snapshotPath", re);
									});
								}
							}, 200)
						}, result => {
							//console.log(result);
						})
						self.$lobster.im.downloadVideo(item.msgID, down => {
							self.$set(item.videoElem, "videoPath", "file://" + down.url);
						}, result => {
							//console.log(result);
							//console.log(parseFloat(result.currentSize / result.totalSize).toFixed(2));
						})

					}

				})
			},
			// 发送文字消息
			sendText() {
				if (this.haveOrder == '0') {
					this.$api.yetOrderMsg('您还没有下单，无法联系医生',
						this.user.touser, this.user.userId,
						this.user.RecordId, this.user.PatientId).then(res => {
						console.log(res);
					}).catch(res => {
						console.log(res);
					});
					return;
				}
				uni.showLoading({
					title: '正在发送'
				})
				this.textFoucs = true;
				if (!this.textMsg || this.textMsg.trim().length == 0) {
					getApp().$util.showToast('发送内容为空');
					return;
				}
				if (this.textMsg.trim().length.length > 4000) {
					getApp().$util.showToast('发送内容最多4000个字');
					return;
				}
				var tex = this.$lobster.im.replaceEmoji(this.textMsg);
				this.sendTextMsg(tex);
				uni.hideLoading();
				this.textMsg = ''; //清空输入框
			},
			//发送文本消息
			sendTextMsg(content) {
				var self = this;
				var textInfo = JSON.parse(JSON.stringify(self.$lobster.im.textInfo));
				var localId = self.$lobster.im.localCustomData(self.user.userId, self.user.touser, self.user
					.businessId);
				textInfo.sender = self.user.userId;
				textInfo.userID = self.user.touser;
				textInfo.sending = true;
				textInfo.msgID = localId;
				var textElem = {
					text: content
				};
				textInfo.textElem = textElem;
				textInfo.timestamp = self.$lobster.im.getTimestamp(); //new Date();
				if (self.platform == 'ios') {
					textInfo.timestamp = self.$lobster.im.getCurrentTime();
				}
				textInfo.sending = true;
				let ctd = {
					businessId: self.user.businessId,
					patId: self.user.patId,
					workId: 0,
					localId: localId
				};
				var cloudCustomData = JSON.stringify(ctd);
				textInfo.cloudCustomData = cloudCustomData;
				self.$store.commit('pushCurrentMessageList', textInfo);
				self.$lobster.im.sendC2CTextMessage("",content, self.user.touser, cloudCustomData, res => {
					console.log(res);
					self.sendback(res, textInfo.cloudCustomData);
				})
			},
			//发送图片消息
			sendImgMsg(content) {
				if (this.haveOrder == '0') {
					this.$api.yetOrderMsg('您还没有下单，无法联系医生',
						this.user.touser, this.user.userId,
						this.user.RecordId, this.user.PatientId).then(res => {
						console.log(res);
					}).catch(res => {
						console.log(res);
					});
					return;
				}
				var self = this;
				var imgInfo = JSON.parse(JSON.stringify(self.$lobster.im.imgInfo));
				var localId = self.$lobster.im.localCustomData(self.user.userId, self.user.touser, self.user
					.businessId);
				imgInfo.sender = self.user.userId;
				imgInfo.userID = self.user.touser;
				imgInfo.sending = true;
				imgInfo.msgID = localId;
				let ctd = {
					businessId: self.user.businessId,
					patId: self.user.patId,
					workId: 0,
					localId: localId
				};
				var cloudCustomData = JSON.stringify(ctd);
				imgInfo.cloudCustomData = cloudCustomData;
				imgInfo.localUrl = content;
				var promise = self.$lobster.im.getImageInfo(content);
				promise.then(rs => {
					var width = parseFloat(rs.width);
					var height = parseFloat(rs.height);
					var p = width / height;
					if (p >= 1) {
						width = self.baseP;
						height = width / p;
					} else {
						height = self.baseP;
						width = height * p
					}
					imgInfo.height = height;
					imgInfo.width = width;;
					var imageList = [{
						"height": imgInfo.height, //rs.height, //图片高度
						"url": content, //图片url
						"uUID": "", //唯一标示用于缓存的key
						"type": 0, //图片类型  0原图  1缩略图  2大图
						"width": imgInfo.width, //rs.width, //图片宽度
						"size": 0, //图片大小
					}];
					imgInfo.timestamp = self.$lobster.im.getTimestamp();
					if (self.platform == 'ios') {
						imgInfo.timestamp = self.$lobster.im.getCurrentTime();
					}
					imgInfo.sending = true;
					imgInfo.imageElem.imageList = imageList;
					self.imglist.push(imgInfo.imageElem.imageList[0].url); //rs.path
					self.$store.commit('pushCurrentMessageList', imgInfo);
					console.log("push");
					self.$lobster.im.sendC2CImgMessage("",content, self.user.touser, cloudCustomData, res => {
						//console.log(res)
						self.sendback(res, imgInfo.cloudCustomData);
					})
				}).catch(res => {
					self.$util.showToast(JSON.stringify(res));
				})
			},
			//发送语音消息
			sendSoundMsg(tempFilePath) {

				if (this.haveOrder == '0') {
					this.$api.yetOrderMsg('您还没有下单，无法联系医生',
						this.user.touser, this.user.userId,
						this.user.RecordId, this.user.PatientId).then(res => {
						console.log(res);
					}).catch(res => {
						console.log(res);
					});
					return;
				}

				var self = this;
				let msg = {
					length: 0,
					url: tempFilePath, //e.tempFilePath,
					upurl: plus.io.convertLocalFileSystemURL(tempFilePath)
				}
				let min = parseInt(self.recordLength / 60);
				let sec = self.recordLength % 60;
				min = min < 10 ? '0' + min : min;
				sec = sec < 10 ? '0' + sec : sec;
				msg.length = self.recordLength;
				var voiceInfo = JSON.parse(JSON.stringify(self.$lobster.im.voiceInfo));
				voiceInfo.sender = self.user.userId;
				voiceInfo.userID = self.user.touser;
				voiceInfo.sending = true;
				voiceInfo.msgID = localId;
				voiceInfo.sending = true;
				var soundElem = {
					"uUID": "", //uuid
					"path": msg.upurl, //路径
					"dataSize": 0, //文件大小
					"duration": msg.length //时长，单位：秒
				};
				if (self.platform == 'ios') {
					voiceInfo.timestamp = self.$lobster.im.getCurrentTime();
				} else {
					voiceInfo.timestamp = self.$lobster.im.getTimestamp();
				}
				voiceInfo.soundElem = soundElem;
				voiceInfo.localUrl = tempFilePath;
				//self.$util.showModal("提示","6",aa=>{},bb=>{},false);
				var localId = self.$lobster.im.localCustomData(self.user.userId, self.user.touser, self.user
					.businessId);
				voiceInfo.msgID = localId;
				let ctd = {
					businessId: self.user.businessId,
					patId: self.user.patId,
					workId:0, 
					localId: localId
				};
				var cloudCustomData = JSON.stringify(ctd);

				voiceInfo.cloudCustomData = cloudCustomData;
				//var w = parseInt(msg.length) * 40;
				voiceInfo.width = self.$lobster.im.soundLength(msg.length, self.winSize
					.screenWidth);
				self.$store.commit('pushCurrentMessageList', voiceInfo);
				self.$lobster.im.sendSoundMessage("",msg.upurl, msg.length, self.user.touser, cloudCustomData, result => {
					//self.$util.showModal("提示",JSON.stringify(res),aa=>{},bb=>{},false);
					self.sendback(result, cloudCustomData);
				})
			},
			//发送短视频
			sendVideoMsg(msg) {
				if (this.haveOrder == '0') {
					this.$api.yetOrderMsg('您还没有下单，无法联系医生',
						this.user.touser, this.user.userId,
						this.user.RecordId, this.user.PatientId).then(res => {
						console.log(res);
					}).catch(res => {
						console.log(res);
					});
					return;
				}
				//console.log(msg);
				var self = this;
				uni.showLoading({
					title: "正在上传..."
				})
				var promise = self.$lobster.im.getVideoThumbnail(msg.upurl);
				promise.then(res => {
					if (res && res.code == 0) {
						console.log("获取封面完毕");
						//ios原生返回的路径无法展示在uniapp端 所以做了保存转换为uniapp能够识别的路径
						var prs = self.$lobster.im.saveFile(res.path);
						prs.then(pps => {
							var item = JSON.parse(JSON.stringify(self.$lobster.im.videoInfo));
							var width = parseFloat(res.width);
							var height = parseFloat(res.height);
							var p = width / height;
							if (p >= 1) {
								width = self.baseP;
								height = width / p;
							} else {
								height = self.baseP;
								width = height * p
							}
							item.height = height;
							item.width = width;
							item.timestamp = self.$lobster.im.getTimestamp();
							if (self.platform == 'ios') {
								item.timestamp = self.$lobster.im.getCurrentTime();
							}
							item.localUrl = msg.upurl;
							var videoElem = {
								"snapshotSize": 0, //截图大小
								"videoUUID": "", //视频文件 ID
								"videoSize": 0, //视频文件大小
								"snapshotPath": pps, //plus.io.convertAbsoluteFileSystem(res.path),//"file://" + res.path, //设置的截图路径
								"snapshotWidth": res.width, //截图宽度
								"videoPath": "file://" + msg.upurl, //视频文件路径（只有发送方才能获取到）
								"snapshotHeight": res.height, //截图高度
								"snapshotUUID": "", //截图 ID，内部标识，可用于外部缓存 key
								"duration": msg.duration //视频时长，单位：秒
							};
							item.sender = self.user.userId;
							item.userID = self.user.touser;
							item.videoElem = videoElem;
							item.sending = true;
							var localId = self.$lobster.im.localCustomData(this.user.userId, this.user.touser, this
								.user
								.businessId);
							item.msgID = localId;
							
							let ctd = {
								businessId: self.user.businessId,
								patId: self.user.patId,
								workId: 0,
								localId: localId
							};
							var cloudCustomData = JSON.stringify(ctd);
							item.cloudCustomData = cloudCustomData;
							self.$store.commit('pushCurrentMessageList', item);
							uni.hideLoading();
							self.hideDrawer();
							//	console.log("upurl:" + msg.upurl);
							plus.zip.compressVideo({
								src: msg.upurl,
								quality: 'medium'
							}, function(e) {
								console.log("压缩视频成功：" + JSON.stringify(e));
								msg.upurl = e.tempFilePath.replace('file://', '');
								//res.path  必须使用ios返回的原生路径
								self.$lobster.im.sendVideoMessage("",msg.upurl, msg.duration, msg.type, res
									.path, self
									.user.touser,
									cloudCustomData, result => {
										//console.log("send");
										console.log(result);
										if (result.code == 0) {
											self.sendback(result, item.cloudCustomData);
										} else {
											self.$util.showToast(result.msg);
										}
									}, proback => {
										//console.log("sendpro");
										//console.log(proback);
									})
							}, function(e) {
								console.log("压缩视频失败：" + JSON.stringify(e));
								uni.hideLoading();
								self.$util.showToast('短视频发送失败');
							});
						})
					} else {
						uni.hideLoading();
						self.$util.showToast('生成封面异常');
					}
				}).catch(res => {
					uni.hideLoading();
					self.$util.showToast('短视频发送失败');
				})
			},

			// 打开抽屉
			openDrawer() {
				if (!this.popupLayerClass) {
					this.popupLayerClass = 'showLayer';
					this.setScallHeight();
				}
			},
			// 隐藏抽屉
			hideDrawer() {
				//console.log('hidd')
				if (this.popupLayerClass) {
					this.popupLayerClass = '';
					this.hideMore = true;
					this.hideEmoji = true;
					this.setScallHeight();
				}


			},
			//选照片 or 拍照
			chooseImage() {
				var self = this;
				uni.showActionSheet({
					itemList: ['拍摄', '从相册选择'],
					success: (res) => {
						if (res.tapIndex == 0) {
							self.$lobster.permission.auth('camera', () => {
								self.chooseImageaction('camera');
							}).then(eee => {
								if (eee && eee == 1) {
									self.chooseImageaction('camera');
								}
							});
						} else {
							self.$lobster.permission.auth('photoLibrary', () => {
								this.chooseImageaction('album');
							}).then(eee => {
								if (eee && eee == 1) {
									this.chooseImageaction('album');
								}
							});
						}
					},
					fail: function(res) {}
				});
			},
			chooseImageaction(type) {
				var self = this;
				uni.chooseImage({
					sourceType: [type],
					sizeType: ['original'], //, 'compressed'可以指定是原图还是压缩图，默认二者都有
					success: (res) => {
						console.log(res)
						res.tempFilePaths.forEach((item) => {
							var imgPath = plus.io.convertLocalFileSystemURL(item)
							self.sendImgMsg(imgPath);
						})

					}
				});
			},
			//监听器
			addListiner() {
				var self = this
				uni.$off("RecvNew");
				uni.$off("RevokedMessage");
				uni.$off("ReadReceipt");
				uni.$on("RevokedMessage", res => {
					console.log(res);
					self.revokeBack(res.msg);
				});
				uni.$on("ReadReceipt", res => {
					console.log(res);
				});
			},

			//获取历史记录
			getHistory() {
				//console.log("history");
				var self = this;
				self.$lobster.im.getC2CHistoryMessageList(self.user.touser, self.pageCount, self.lastMessageID, res => {
					self.loading = '';
					console.log(res);
					var list = res.message;
					self.messageConverter(list);
					self.msgList.push(...list);
					if (res.message != null && res.message.length > 0) {
						self.lastMessageID = res.message[0].msgID;
					}

					//console.log(self.lastMessageID);
					uni.hideLoading();
				})
			},
			//加载更多
			loadMore() {
				var self = this;
				//console.log("loadMore_" + self.lastMessageID);
				self.$lobster.im.getC2CHistoryMessageList(self.user.touser, self.pageCount, self.lastMessageID, res => {
					//console.log(res);
					var list = res.message;
					// if (list.length > 0) {
					// 	list = list.filter(p => p.cloudCustomData.split('^')[0] == self.user.businessId);
					// }
					let kid = '';
					if (self.msgList.length) {
						kid = 'id_' + self.msgList[self.msgList.length - 1].msgID
					}
					self.messageConverter(list);
					self.msgList.splice(0, 0, ...list)
					//self.$store.commit('unshiftCurrentMessageList', list);
					console.log(res.message);
					if (list != null && list.length > 0) {
						self.lastMessageID = list[0].msgID;
					} else {
						self.refresher = false;
					}
					self.$nextTick(() => {
						self.scrollToView = 'id_' + list[list.length - 1].msgID;
						return;

					})
					console.log(self.lastMessageID);
					self.loading = '';
					uni.hideLoading();
					self.triggered = false;
					self._freshing = false;
				})
			},

			//聊天的节点加上外层的div
			nodesFliter(str) {
				str = str.replace(/\n/g, '<br>')
				let nodeStr = '<div style="align-items: center;word-wrap:break-word;">' + str + '</div>'
				return nodeStr
			},
			//时间过滤
			timeFliter(timer, index) {
				if (this.platform == 'ios') {
					let timeData = new Date(timer);
					let str = '';
					var preStamp = timeData;
					if (index > 0) {
						preStamp = new Date(this.msgList[index - 1].timestamp);
						var sjc = Math.floor((timeData.getTime() - preStamp.getTime()) / 1000 / 60);
						if (sjc < 3) {
							return "";
						}
					}
					var date = new Date();
					if (timeData.toDateString() == date.toDateString()) {
						str = this.$lobster.im.dateTimeFliter(timeData, 3, false, true);
					} else {
						str = this.$lobster.im.dateTimeFliter(timeData, 4, false, true);
					}
					return str
				} else {
					let timeData = new Date(timer * 1000);
					//console.log(timeData + '_' + timer);
					let str = '';
					var preStamp = timeData;
					if (index > 0) {
						preStamp = new Date(this.msgList[index - 1].timestamp * 1000);
						var sjc = Math.floor((timeData - preStamp) / 1000 / 60);
						if (sjc < 3) {
							return "";
						}
					}

					var date = new Date();
					if (timeData.toDateString() == date.toDateString()) {
						str = this.$lobster.im.dateTimeFliter(timeData, 3, false, true);
					} else {
						str = this.$lobster.im.dateTimeFliter(timeData, 4, false, true);
					}
					return str
				}
			},
			// 接受消息(定位消息)
			screenMsg() {
				// if (newVal.length == 0 && oldVal.length == 0) {
				// 	return;
				// }
				var self = this;
				if (self.msgList.length > 0) {
					self.$nextTick(() => {
						self.scrollToView = 'id_' + self.msgList[self.msgList.length - 1].msgID;
						//console.log(self.scrollToView);
					});
				}
			},
			//获取焦点，如果不是选表情ing,则关闭抽屉
			textareaFocus() {
				//console.log(this.popupLayerClass + '_' + this.hideMore);
				//if (this.popupLayerClass == 'showLayer' && this.hideMore == false) {
				this.hideDrawer();
				//this.textFoucs = true;
				//}
			},
			// 切换语音/文字输入
			switchVoice() {
				//this.hideDrawer();
				this.isVoice = this.isVoice ? false : true;
				if (this.isVoice)
					this.hideDrawer();
			},
			//更多功能(点击+弹出)
			showMore() {
				this.isVoice = false;
				this.hideEmoji = true;
				if (!this.popupLayerClass) {
					this.hideMore = false;
					this.textFoucs = false;
					this.openDrawer();
				} else {
					this.hideDrawer();
					this.textFoucs = true;
					//
				}
			},
			//行高变化更改事件
			lineChange(e) {
				if (e.detail.lineCount)
					this.setHeight.line = e.detail.lineCount;
				else this.setHeight.line = 1;
				if (this.setHeight.line > 4) this.setHeight.line = 4;
				//console.log(e.detail.lineCount)
				this.$nextTick(() => {
					uni.createSelectorQuery().in(this).select(".input-box").boundingClientRect(data => {
						this.setHeight.inputHeight = data.height;
						this.setScallHeight();
					}).exec();
				})
			},
			//键盘高度变化更改事件
			keyboardheightchange(e) {
				this.keyHeight = e.detail.height;
				this.setHeight.keyHeight = e.detail.height;
				//console.log(e);
				this.setScallHeight()
			},
			//录制视频
			recordVideo() {
				this.getVideo('camera');
			},
			discard() {
				return;
			},
			// 录音开始
			voiceBegin: throttle(function(e) {
				var self = this;
				if (self.clickIng) return;
				self.clickIng = true;
				self.$lobster.permission.auth('record', () => {
					if (e.touches.length > 1) {
						self.clickIng = false;
						return;
					}
					self.initPoint.Y = e.touches[0].clientY;
					self.initPoint.identifier = e.touches[0].identifier;
					self.RECORDER.start({
						format: "mp3"
					}); //录音开始,
					self.clickIng = false;
				}).then(res => {
					if (res && res == 1) {
						if (e.touches.length > 1) {
							self.clickIng = false;
							return;
						}
						self.initPoint.Y = e.touches[0].clientY;
						self.initPoint.identifier = e.touches[0].identifier;
						self.RECORDER.start({
							format: "mp3"
						}); //录音开始,
					} else {
						self.clickIng = false;
					}
				})
			}, 1000),
			// 录音中(判断是否触发上滑取消发送)
			voiceIng(e) {
				// if (!this.recording) {
				// 	this.clickIng=false;
				// 	return;
				// }
				let touche = e.touches[0];
				//上滑一个导航栏的高度触发上滑取消发送
				if (this.initPoint.Y - touche.clientY >= uni.upx2px(100)) {
					this.willStop = true;
					this.recordTis = '松开手指 取消发送'
				} else {
					this.willStop = false;
					this.recordTis = '手指上滑 取消发送'
				}
			},
			// 录音被打断
			voiceCancel() {
				//this.clickIng=false;
				this.recording = false;
				this.voiceTis = '按住 说话';
				this.recordTis = '手指上滑 取消发送'
				this.willStop = true; //不发送录音
				this.RECORDER.stop(); //录音结束
			},
			// 结束录音
			voiceEnd(e) {
				// if (!this.recording) {
				// 	this.clickIng=false;
				// 	return;
				// }
				//this.clickIng=false;
				this.recording = false;
				this.voiceTis = '按住 说话';
				this.recordTis = '手指上滑 取消发送'
				this.RECORDER.stop(); //录音结束
			},
			//录音开始UI效果
			recordBegin(e) {
				this.recording = true;
				this.voiceTis = '松开 结束';
				this.recordLength = 0;
				if (this.recordTimer) {
					clearInterval(this.recordTimer);
					//this.intervalIng = false;
					this.recordTimer = null;
					this.recordLength = 0;
				}
				this.recordTimer = setInterval(() => {
					this.recordLength++;
					if (this.recordLength >= (this.soundMax - this.soundcountdown)) {
						this.recordTis = this.soundMax - this.recordLength + '秒后自动发送';
					}
					if (this.recordLength >= this.soundMax) {
						this.voiceEnd();
					}
				}, 1000)
			},
			//录音结束(回调文件)
			recordEnd(e) {
				if (this.recordTimer) {
					clearInterval(this.recordTimer);
					this.recordTimer = null;
				}
				if (!this.willStop) {
					if (this.recordLength < 1) {
						this.clickIng = false;
						this.$util.showToast("说话时间太短");
						return;
					}
					this.sendSoundMsg(e.tempFilePath);
				} else {
					console.log('取消发送录音');
				}
				this.willStop = false;
				this.clickIng = false;
			},
			// 播放语音
			playVoiceUrl(item) {
				//console.log(item);
				this.AUDIO.src = "file://" + item.soundElem.path;
				var playId = this.playSoundMsgId;
				this.playSoundMsgId = item.msgID;
				//console.log(playId + '||' + this.playSoundMsgId);
				this.$nextTick(function() {
					//console.log('play');
					if (item.msgID == playId) {
						//console.log("stop");
						this.playSoundMsgId = "";
						this.AUDIO.stop();
					} else {
						//console.log("pp");
						this.AUDIO.play();
					}
				});
			},
			hidePayer() {
				this.VideoContext.pause();
				this.showVideo = false;
			},
			playVideo(item) {
				this.showVideo = true;
				this.VideoContext = uni.createVideoContext('myVideo');
				if (item.elemType == 11) {
					this.videoUrl = item.videoPath;
				} else {
					this.videoUrl = item.videoElem.videoPath;
				}
				this.VideoContext.play();
			},
			timeConverter(duration) {
				var theTime = parseInt(duration); // 秒
				var middle = 0; // 分
				var hour = 0; // 小时

				if (theTime > 60) {
					middle = parseInt(theTime / 60);
					theTime = parseInt(theTime % 60); //余数 换算成分钟以后剩余的秒数
					var result = "" + (parseInt(theTime) < 10 ? '0' + theTime : theTime);
					result = "" + (parseInt(middle) < 10 ? '0' + middle : middle) + ":" + result;
				} else {
					result = "00:" + (theTime < 10 ? '0' + theTime : theTime);
				}
				return result;
			},

			//发送视频
			sendVideoMessage() {
				uni.showActionSheet({
					itemList: ['相册', '拍摄'],
					success: (res) => {
						//console.log(res);
						if (res.tapIndex == 0) {
							this.getVideo('album');
						} else {
							this.getVideo('camera');
						}
					},
					fail: function(res) {
						//console.log(res.errMsg);
					}
				});
			},
			//取到视频
			getVideo(type) {
				var self = this;
				if (type == 'camera') {
					self.$lobster.permission.auth('cameraandrecord', () => {
						self.chooseVideoself(type)
					}).then(res => {
						if (res && res == 1) {
							self.chooseVideoself(type);
						}
					})
				} else {
					self.$lobster.permission.auth('photoLibrary', () => {
						self.chooseVideoself(type)
					}).then(res => {
						if (res && res == 1) {
							self.chooseVideoself(type);
						}
					})
				}
			},
			chooseVideoself(type) {
				var self = this;
				uni.chooseVideo({
					count: 1,
					sourceType: [type],
					maxDuration: 30,
					compressed: false, //压缩 文件
					success: function(res) {
						if (res.size > (1024 * 1024 * 100)) {
							plus.nativeUI.toast('请勿超过100M,请重新上传');
							return;
						}
						self.hideDrawer();

						if (self.haveOrder == '0') {
							self.$api.yetOrderMsg('您还没有下单，无法联系医生',
								self.user.touser, self.user.userId,
								self.user.RecordId, self.user.PatientId).then(res => {
								//console.log(res);
							}).catch(res => {
								console.log(res);
							});
							return;
						}

						if (type == "album") {
							self.albumVideo(res);
						} else {
							self.cameraVideo(res);
						}
					},
					fail: function(res) {},
					complete: function(res) {},
				});
			},

			//abm 相册视频处理
			albumVideo(res) {
				var self = this;
				var savedFilePath = plus.io.convertLocalFileSystemURL(res.tempFilePath);
				let filetype = savedFilePath.slice(savedFilePath.lastIndexOf('.') + 1);
				uni.showLoading({
					title: "加载中..."
				})
				let msg = {
					upurl: savedFilePath, //上传的视频路径
					type: filetype, //视频类型
					duration: parseInt(res.duration), //时长
					size: res.size, //视频大小
				};
				self.sendVideoMsg(msg);
			},

			//拍摄视频处理
			cameraVideo(res) {
				var self = this;
				uni.showLoading({
					title: "正在保存..."
				})
				uni.saveFile({
					tempFilePath: res.tempFilePath,
					success: function(resa) {
						var savedFilePath = plus.io.convertLocalFileSystemURL(resa.savedFilePath);
						//console.log("savepath:" + savedFilePath);
						let filetype = savedFilePath.slice(savedFilePath.lastIndexOf('.') + 1);
						uni.showLoading({
							title: "加载中..."
						})

						let msg = {
							upurl: savedFilePath, //上传的视频路径
							type: filetype, //视频类型
							duration: parseInt(res.duration), //时长
							size: res.size, //视频大小
						};
						self.sendVideoMsg(msg);
					}
				});
			},
			//处理发送短视频后的回调
			sendback(res, cloudCustomData) {
				var self = this;
				if (res.code == 0) {
					var message = res.message;
					self.msgList.forEach((it, idx) => {
						if (it.cloudCustomData == cloudCustomData) {
							Vue.set(it, "msgID", message.msgID);
							Vue.set(it, "status", 2);
							Vue.set(it, "cloudCustomData", message.cloudCustomData);
							Vue.set(it, "random", message.random);
							Vue.set(it, "faceUrl", message.faceUrl);
							//Vue.set(it, "timestamp", message.timestamp);
							Vue.set(it, "priority", message.priority);
							Vue.set(it, "read", message.read);
							Vue.set(it, "peerRead", message.peerRead);
							Vue.set(it, "seq", message.seq);
							Vue.set(it, "nickName", message.nickName);
							Vue.set(it, "msgID", message.msgID);
							Vue.set(it, "sending", false);
							switch (message.elemType) {
								case 1: //文本消息
									Vue.set(it, "textElem", message.textElem);
									break;
								case 2: //自定义 
									break;
								case 3: //图片消息
									//由于覆盖数据会导致查看大图失败，暂时去掉
									//Vue.set(it, "imageElem", message.imageElem);   
									break;
								case 4: //语音消息
									Vue.set(it, "soundElem", message.soundElem);
									break;
								case 5: //短视频
									var video = message.videoElem;
									Vue.set(it, "videoElem", video);
									break;
							}
							//console.log(it);
						}
					})
				} else {
					//self.$util.showModal("senderror",JSON.stringify(res),aa=>{},bb=>{},false);
					if (res.code == 6014) {
						self.$util.showModal("提示", "您已下线，请重新登录", aa => {
							imLogin.login(self.userId, res => {
								self.addListiner();
							});
						}, bb => {}, true);
					} else {
						self.$util.showToast(self.$lobster.im.codeConverter(res.code));
					}
					self.msgList.forEach((it, idx) => {
						if (it.cloudCustomData == cloudCustomData) {
							Vue.set(it, "status", 10);
						}
					});
				}
			},
			//撤回处理 
			revokeBack(msgId) {
				this.setMsgStatus(msgId, 6);
			},
			//修改消息状态
			setMsgStatus(msgId, status) {
				var self = this;
				self.msgList.forEach((it, idx) => {
					if (it.msgID == msgId) {
						Vue.set(it, "status", status);
					}
				})
			},
		 
			//进入视频房间
			async videoChat() {
				var that = this;
				let data = that.user.businessId;
				that.$lobster.im.invite(that.user.touser, data, false, 60, res => {
					//that.$util.showToast(JSON.stringify(res));
					uni.navigateTo({
						url: '/pages/im/callVideo/callVideo?userId=' + that.user.userId +
							'&roomId=' + that.user.businessId
					})
				})
			},
			async initBaseData() {
				if (this.isInit) return;
				this.isInit = true;
				this.$store.commit('resetCurrentConversation', this.user.touser);
				this.$lobster.im.markC2CMessageAsRead(this.user.touser, res => {
					//console.log(res)
				});
				this.emojiList = this.$lobster.im.emojiList;
				//console.log(this.emojiList);
				uni.showLoading({
					title: "正在初始化数据",
					mask: true
				})
				this.addListiner();
				this.getHistory();

				this.RECORDER.onStart((e) => {
					//console.log(e)
					this.recordBegin(e);
				})
				//录音结束事件
				this.RECORDER.onStop((e) => {
					//console.log(e)
					this.recordEnd(e);
				})
				this.RECORDER.onError((e) => {
					console.log(e);
				})
				//语音自然播放结束
				this.AUDIO.onEnded((res) => {
					this.playSoundMsgId = '';
					//console.log("playEnd");
				});
				this.AUDIO.onError((res) => {
					console.log(res);
				});
				var self = this;
				uni.$on("exit-room", function() {
					self.hideDrawer();
				});
				self.getWindowSize();

				// self._freshing = false;
				// setTimeout(() => {
				// 	self.triggered = true;
				// }, 1000)
				uni.hideLoading();
			},

			//预览图片
			previewImage(e) {
				var current = e.currentTarget.dataset.url;
				//console.log(current);
				var urls = this.imglist;
				uni.previewImage({
					current: current,
					urls: urls
				})
			},
			// 选择表情
			chooseEmoji() {
				this.hideMore = true;
				if (this.hideEmoji) {
					this.hideEmoji = false;
					this.openDrawer();
				} else {
					this.hideDrawer();
				}
			},
			//添加表情
			addEmoji(em) {
				this.textMsg += em.alt;
			},
			/* 获取窗口尺寸 */
			getWindowSize() {
				uni.getSystemInfo({
					success: (res) => {
						//console.log(res);
						this.winSize = {
							"width": res.windowWidth,
							"height": res.windowHeight,
							"screenWidth": res.screenWidth,
							statusBarHeight: res.statusBarHeight,
							screenHeight: res.screenHeight,
							navigationBarHeight: res.navigationBarHeight,
							titleBarHeight: res.titleBarHeight,
						}
					}
				})
			},
			/* 长按监听 */
			onLongPress(e) {
				//console.log(e);
				var sender = e.currentTarget.dataset.sender;
				//if (sender != this.user.userId) return;
				var timestamp = e.currentTarget.dataset.timestamp;
				var item = e.currentTarget.dataset.item;
				var nowstamp = new Date();
				if (this.platform == 'ios') {
					var sjc = Math.floor((nowstamp.getTime() - timestamp.getTime()) / 1000 / 60);
					if (sjc >= 2) {
						this.popButton[0].show = false;
					} else {
						this.popButton[0].show = true;
					}
				} else {
					//console.log(timestamp)
					var stamp = timestamp * 1000;
					var timepare = this.$lobster.im.compareStamp(nowstamp, stamp);
					//console.log(timepare);
					if (timepare >= 2) {
						this.popButton[0].show = false;
					} else {
						this.popButton[0].show = true;
					}
				}
				if (item.elemType != 1) { //不是文本不能复制
					this.popButton[1].show = false;
				}
				if (sender != this.user.userId) { //不是自己的数据不能撤回
					this.popButton[0].show = false;
				}
				var showLen = this.popButton.filter(p => p.show == true);
				if (!showLen || showLen.length == 0) return;
				let [touches, style, index] = [e.touches[0], "", e.currentTarget.dataset.index];

				/* 因 非H5端不兼容 style 属性绑定 Object ，所以拼接字符 */
				if (touches.clientY > (this.winSize.height / 2)) {
					style = `bottom:${this.winSize.height-touches.clientY}px;`;
				} else {
					style = `top:${touches.clientY}px;`;
				}
				if (touches.clientX > (this.winSize.width / 2)) {
					style += `right:${this.winSize.width-touches.clientX}px`;
				} else {
					style += `left:${touches.clientX}px`;
				}

				this.popStyle = style;
				this.pickerMsgIndex = Number(index);
				this.showShade = true;
				this.$nextTick(() => {
					setTimeout(() => {
						this.showPop = true;
					}, 10);
				});
			},
			/* 隐藏弹窗 */
			hidePop() {
				this.showPop = false;
				this.pickerMsgIndex = -1;
				setTimeout(() => {
					this.showShade = false;
				}, 250);
			},
			/* 选择菜单 */
			pickerMenu(e) {
				//console.log(e);
				var self = this;
				let index = Number(e.currentTarget.dataset.index);
				//console.log(index);
				//console.log(self.msgList[self.pickerMsgIndex]);
				var code = e.currentTarget.dataset.code;
				var msgId = self.msgList[self.pickerMsgIndex].msgID;
				switch (code) {
					case 'ch':
						self.$lobster.im.revokeMessage(msgId, res => {
							//console.log(res);
							if (res.code == 0) {
								self.revokeBack(msgId);
							} else {
								// self.$util.showToast(res.code +'|' + '撤回失败');
								var tip = self.$lobster.im.codeConverter(res.code)
								plus.nativeUI.toast(res.code + '|' + tip || '撤回失败');
							}
						})
						break;
					case 'fz':
						this.copyData(self.msgList[self.pickerMsgIndex].textElem.text);
						break;
					default:
						break;
				}
				/* 
				 因为隐藏弹窗方法中会将当前选择的用户下标还原为-1,
				 如果行的菜单方法存在异步情况，请在隐藏之前将该值保存，或通过参数传入异步函数中
				 */
				this.hidePop();
			},
			//监听image加载完成
			onImageLoad(index) {
				this.$set(this.msgList[index], 'loaded', 'loaded');
			},
			//监听image加载失败
			onImageError(index) {
				this.msgList[index].imageElem.imageList[0].url = '/static/errorImage.jpg';
			},
			//文字双击
			fndbClick(item) {
				this.index = this.index == 0 ? 1 : this.index + 1;
				if (this.index == 1) {
					this.start_time = new Date().getTime();
					setTimeout(() => {
						this.index = this.start_time = this.end_time = 0;
						//this.doubleText='';
					}, 200)
				} else if (this.index == 2) {
					this.end_time = new Date().getTime();
					if (this.end_time - this.start_time < 300) {
						this.showSceen = true;
						this.doubleText = item.textElem.text;
					}
					this.index = this.start_time = this.end_time = 0;
				}
			},
			//重新发送
			sendAgain(item) {
				//console.log(item);
				var self = this;
				self.setMsgStatus(item.msgID, 7);
				switch (item.elemType) {
					case 1: //文本
						self.sendTextMsg(item.textElem.text);
						break;
					case 2:
						break;
					case 3: //图片
						if (item.localUrl) {
							self.sendImgMsg(item.localUrl);
						}
						break;
					case 4: //语音
						if (item.localUrl) {
							self.sendSoundMsg(item.localUrl);
						}
						break;
					case 5:
						if (item.localUrl) {
							var msg = {};
							msg.upurl = item.localUrl;
							msg.duration = item.videoElem.duration;
							msg.type = item.localUrl.slice(item.localUrl.lastIndexOf('.') + 1);;
							self.sendVideoMsg(msg);
						}
						break;
					default:
						break;
				}
			},
			hideSceen() {
				this.showSceen = false;
			},

			//自定义下拉刷新控件被下拉
			onPulling(e) {
				//console.log("onpulling", e);
			},
			//下拉加载更多
			onRefresh() {
				//console.log("onRefresh");
				if (this._freshing) return;
				this.triggered = true;
				this._freshing = true;
				this.loadMore();

			},
			onRestore() {
				this.triggered = 'restore'; // 需要重置
				console.log("onRestore");
			},
			onAbort() {
				console.log("onAbort");
			},
			//查看详情
			persondetail(url) {
				if (url) {
					this.$util.navigateTo(url)
				}
			},
			//病历处方
			medPres() {
				var url = '/pages/service/furtherconsultation/presmain';
				this.$util.navigateTo(url);
			},
			itemClick(item) {
				//console.log(item);
				this.$emit('customEvent', item);
			},
			//快捷回复
			fastreply() {

			},
			//复制
			copyData(text) {
				uni.setClipboardData({
					data: text,
					success: function() {
						//uni.hideToast()
						console.log('success');
					}
				});
			},

			//自定义消息转换器
			customMsgConverter(item, res) {
				if (res && res.code == 0) {
					try {
						var dd = JSON.parse(res.data);
						//console.log(dd);
						if (!dd) return;
						var info = JSON.parse(dd.data);
						if (!info) return;
						if (dd.customType == 'video') { //视频
							this.customVideoConverter(item, info)
						} else if (dd.customType == 'text') { //文本
							this.customTextConverter(item, info)
						} else if (dd.customType == 'question') { //问卷
							this.customQuestionConverter(item, info)
						} else if (dd.customType == 'medicine') { //购药
							this.customMedicineConverter(item, info)
						} else if (dd.customType == 'yetOrder') { //未下单
							this.customYetOrderConverter(item, info)
						}
					} catch (rrr) {
						console.log(rrr);
					}
				}
			},
			//自定义视频消息转换
			customVideoConverter(item, info) {
				var width = parseFloat(info.ThumbWidth);
				var height = parseFloat(info.ThumbHeight);
				var p = width / height;
				if (p >= 1) {
					width = this.baseP;
					height = width / p;
				} else {
					height = this.baseP;
					width = height * p
				}
				Vue.set(item, "elemType", 11);
				Vue.set(item, "Second", info.VideoSecond);
				Vue.set(item, "height", height);
				Vue.set(item, "width", width);
				Vue.set(item, "snapshotPath", info.ThumbUrl);
				Vue.set(item, "videoPath", info.VideoUrl);
			},
			//自定义文本消息转换
			customTextConverter(item, info) {
				Vue.set(item, "elemType", 100);
				Vue.set(item, "Text", info.Text);
			},
			//自定义消息问卷转换
			customQuestionConverter(item, info) {
				Vue.set(item, "elemType", 12);
				Vue.set(item, "QuestionId", info.QuestionId);
				Vue.set(item, "Title", info.Title);
				Vue.set(item, "Describe", info.Describe);
				Vue.set(item, "Link", info.Link);
				Vue.set(item, "Img", info.Img);
			},
			//自定义消息购药转换
			customMedicineConverter(item, info) {
				Vue.set(item, "elemType", 102);
				Vue.set(item, "Title", info.Title);
				Vue.set(item, "Describe", info.Describe);
				Vue.set(item, "Link", info.Link);
				Vue.set(item, "Img", info.Img);
			},
			customYetOrderConverter(item, info) {
				Vue.set(item, "elemType", 104);
				Vue.set(item, "Text", info.Text);
				Vue.set(item, "Link", info.Link);
			},
			customMsgClick(item) {
				//console.log(item.Link);
				this.$emit("click", item)
				if (item.Link) {
					this.$util.navigateTo(item.Link);
				}
			}
		},
		mounted() {
			this.platform = uni.getSystemInfoSync().platform;
			this.getWindowSize();
			this.setScallHeight();
			if (this.user && this.user.userId) {
				this.initBaseData();
			}
		},
		beforeDestroy() {
			//console.log("beforedestroy");
			this.msgList = [];
			this.imglist = [];
			this.AUDIO.destroy();
			this.$store.commit('resetCurrentConversation', this.user.touser);
			uni.$off("RecvNew");
			uni.$off("RevokedMessage");
			uni.$off("ReadReceipt");
		}
	}
</script>

<style lang="scss" scoped>
	@import '../css/style.scss'; 


	page {
		background-color: #EDEDED !important;
	}

	.tip {
		color: #555;
		font-size: 28rpx;
	}
</style>
